const Cookies = require('cookies');
const formidable = require('formidable');
const multiparty = require('multiparty');
const path = require('path');

let postImgHandler = function (req,res) {

    let form = new multiparty.Form();//新建表单
    //设置编辑
    form.encoding = 'utf-8';
    //设置图片存储路径
    form.uploadDir = path.join(__dirname,"../public/images/1/");
    form.keepExtensions = true;   //保留后缀
    form.maxFieldsSize = 2*1024*1024; //内存大小
    form.maxFilesSize= 5*1024*1024;//文件字节大小限制，超出会报错err

    //表单解析
    form.parse(req, function(err,fields,files) {
        //报错处理
        if(err){
            console.log(err);
            let u={"error" :1,"message":'请上传5M以图片'};
            res.end(JSON.stringify(u));
            return false;
        }

        //获取路径
        console.log(files)
        let oldpath=files['file'][0]['originalFilename'];

        //文件后缀处理格式
        let suffix;
        if(oldpath.indexOf('.jpg')>=0){
            suffix='.jpg';
        }else if(oldpath.indexOf('.png')>=0){
            suffix='.png';
        }else if(oldpath.indexOf('.gif')>=0){
            suffix='.gif';
        }else{
            let u={"error" :1,"message":'请上传正确格式'};
            res.end(JSON.stringify(u));
            return false;
        }

        let url=path.join(__dirname,"../public/images/1/"+Date.now()+suffix);
        let fs=require('fs');
        //给图片修改名称
        fs.renameSync(files['file'][0]['path'],path.join(__dirname,"../public/images/1/"+oldpath));
        let u={ "error" : 0, "url" : '/'+url};
        res.end(JSON.stringify(u));
    });
};

module.exports.postImgHandler = postImgHandler;
